#!/usr/bin/env python3
"""
自动生成符合 Google 风格的 Python 项目目录结构
将在当前脚本所在目录生成项目文件
"""

import os
from pathlib import Path

# 基础目录结构模板
TEMPLATE = {
    "README.md": "# Stock Analysis API\n\n基于 FastAPI 的股票数据接口服务",
    "requirements.txt": "fastapi>=0.95.0\nuvicorn>=0.21.0\npandas>=1.5.0\nakshare>=1.3.0",
    "requirements-dev.txt": "black>=23.0\nmypy>=1.0\npytest>=7.0",
    "pyproject.toml": """[project]
name = "stock_api"
version = "0.1.0"
description = "Stock data API service"
authors = [{name = "Your Name", email = "your.email@example.com"}]
dependencies = [
    "fastapi>=0.95.0",
    "uvicorn>=0.21.0",
    "pandas>=1.5.0",
    "akshare>=1.3.0"
]

[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
""",
    ".gitignore": """# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]

# Environment variables
.env

# IDE
.vscode/
.idea/
""",
    "src/__init__.py": "# Package initialization",
    "src/main.py": """from fastapi import FastAPI
from .api.routers import stocks, ws
from .core.config import settings

app = FastAPI(
    title=settings.api_title,
    debug=settings.api_debug,
)

# Include routers
app.include_router(stocks.router, prefix="/api/stocks", tags=["stocks"])
app.include_router(ws.router, prefix="/ws", tags=["websocket"])

@app.get("/")
async def health_check():
    return {"status": "healthy"}
""",
    "src/api/__init__.py": "# API module",
    "src/api/routers/__init__.py": "# API routers",
    "src/api/routers/stocks.py": """from fastapi import APIRouter
from ..services.stock_service import get_history_data
from ..data.schema import StockHistoryResponse

router = APIRouter()

@router.get("/history", response_model=StockHistoryResponse)
async def get_history(stock_code: str, days: int = 30):
    \"\"\"获取股票历史数据\"\"\"
    return await get_history_data(stock_code, days)
""",
    "src/api/routers/ws.py": """from fastapi import WebSocket, APIRouter
import asyncio
import random

router = APIRouter()

@router.websocket("/realtime")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = {
            "time": "2023-01-01T00:00:00",  # 替换为实际数据
            "price": round(100 + random.uniform(-2, 2), 2),
            "volume": random.randint(1000, 10000)
        }
        await websocket.send_json(data)
        await asyncio.sleep(1)
""",
    "src/core/__init__.py": "# Core utilities",
    "src/core/config.py": """from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    api_title: str = "Stock API"
    api_debug: bool = False
    cache_ttl: int = 300  # 5分钟缓存

    class Config:
        env_file = ".env"

settings = Settings()
""",
    "src/data/__init__.py": "# Data data",
    "src/data/schema.py": """from datetime import date
from pydantic import BaseModel

class StockHistoryResponse(BaseModel):
    dates: list[date]
    prices: list[float]
    volume: list[int]
""",
    "src/services/__init__.py": "# Business logic",
    "src/services/stock_service.py": """import akshare as ak
from ..data.schema import StockHistoryResponse

async def get_history_data(stock_code: str, days: int) -> StockHistoryResponse:
    \"\"\"获取股票历史数据（示例）\"\"\"
    df = ak.stock_zh_a_hist(symbol=stock_code, period="daily", adjust="hfq")
    df = df.tail(days)
    return StockHistoryResponse(
        dates=df["日期"].tolist(),
        prices=df["收盘"].tolist(),
        volume=df["成交量"].tolist()
    )
""",
    "tests/unit/__init__.py": "# Unit tests",
    "tests/unit/test_stocks.py": """from fastapi.testclient import TestClient
from src.main import app

client = TestClient(app)

def test_read_history():
    response = client.get("/api/stocks/history?stock_code=000001&days=10")
    assert response.status_code == 200
""",
    "scripts/deploy.sh": """#!/bin/bash
# 示例部署脚本
echo "Deploying stock API..."
uvicorn src.main:app --host 0.0.0.0 --port 8000
"""
}



def create_project(base_path: Path):
    """生成项目目录和文件"""
    for rel_path, content in TEMPLATE.items():
        path = base_path / rel_path
        path.parent.mkdir(parents=True, exist_ok=True)
        with open(path, "w", encoding="utf-8") as f:
            f.write(content)
        print(f"Created: {path}")

    # 设置可执行权限
    (base_path / "scripts/deploy.sh").chmod(0o755)


if __name__ == "__main__":
    # 获取当前脚本所在目录作为项目根目录
    project_path = Path(__file__).parent.absolute()
    print(f"将在当前目录生成项目: {project_path}")

    # 检查是否已存在关键文件（避免覆盖）
    if (project_path / "src/main.py").exists():
        print("错误: 目标目录已存在项目文件！")
        exit(1)

    create_project(project_path)
    print(f"\n项目已生成在: {project_path}")
    print("下一步:")
    print("1. cd", project_path)
    print("2. pip install -r requirements.txt")
    print("3. uvicorn src.main:app --reload")